前面因為一些因素中斷了比賽,決定在此重新參賽。
先前連結
那我們就廢話不多說直接進入,我們的重點待辦清單。
我們先做我們的主頁面,如下圖。
我的習慣會把頁面,放在screens底下,
然後把頁面會使用到的小組件,放在widgets底下
我這邊的 main.dart ,把我們的todos_homepage.dart引入,做簡單的home頁面的渲染。
import 'package:flutter/material.dart';
import './screens/todos_homepage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TodosHomepage(),
    );
  }
}
我這邊的 todo_tile.dart,這邊使用StatefulWidget,因為我在這邊存所有的代辦事項資料。
import 'package:flutter/material.dart';
import '../widgets/todo_tile.dart';
class TodosHomepage extends StatefulWidget {
  @override
  _TodosHomepageState createState() => _TodosHomepageState();
}
class _TodosHomepageState extends State<TodosHomepage> {
  List<Map<String, dynamic>> todos = [
    {"title": "Test 1", "description": "abc123 def456", "done": false},
    {"title": "Test 2", "description": "abc123 def456", "done": true},
    {"title": "Test 3", "description": "abc123 def456", "done": false},
    {"title": "Test 4", "description": "abc123 def456", "done": false},
  ];
  void toggleDoneHandler(index, value) {
    setState(() {
      todos[index]['done'] = value;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Todos'),
      ),
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (ctx, i) => TodoItem(
          title: todos[i]['title'],
          done: todos[i]['done'],
          toggleDone: toggleDoneHandler,
          index: i,
        ),
      ),
    );
  }
}
再來第三個檔案是 todo_tile.dart ,我們這邊有用到dart的 Constructor。
import 'package:flutter/material.dart';
class TodoItem extends StatelessWidget {
  final int index;
  final String title;
  final bool done;
  final Function toggleDone;
  TodoItem({this.title, this.done, this.toggleDone, this.index});
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        title,
        style: TextStyle(
          fontSize: 18,
          decoration: done ? TextDecoration.lineThrough : null,
        ),
      ),
      leading: Checkbox(
        activeColor: Colors.lightBlueAccent,
        value: done,
        onChanged: (val) {
          toggleDone(index, val);
        },
      ),
    );
  }
}
這樣就可以建立起第一個主頁面了哦。